package org.example.test.controller;

import org.example.test.dal.entity.Favorites;
import org.example.test.dal.entity.Product;
import org.example.test.request.ProductRequest;
import org.example.test.response.CommonResponse;
import org.example.test.response.ResponseBuilder;
import org.example.test.service.FavoritesService;
import org.example.test.service.ProductService;
import org.example.test.utils.SaveImage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;  // 商品服务层

    @Autowired
    private FavoritesService favoritesService;  // 收藏服务层

    /**
     * 上传商品图片
     * @param image 图片文件（Multipart格式）
     * @return 图片存储路径（成功）或错误信息（失败）
     */
    @PostMapping("/uploadImage")
    public CommonResponse<String> uploadImage(@RequestParam("image") MultipartFile image) {
        try {
            String imagePath = SaveImage.saveFile(image);  // 调用工具类保存图片
            return ResponseBuilder.success(imagePath);  // 返回图片访问路径
        } catch (IOException e) {
            return ResponseBuilder.error("上传图片失败: " + e.getMessage());
        }
    }

    /**
     * 发布新商品
     * @param productRequest 商品请求参数（名称、价格、分类等）
     * @return 操作结果（成功返回"0"）
     */
    @PostMapping("/publishProduct")
    public CommonResponse generateProduct(@RequestBody ProductRequest productRequest) {
        try {
            LOGGER.info("Generate product request: {}", productRequest);
            productService.addProduct(productRequest);  // 调用服务层添加商品
            return ResponseBuilder.success("0");  // 约定成功返回"0"
        } catch (Exception e) {
            LOGGER.error("Error generating product", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 编辑商品信息
     * @param productId 商品ID
     * @param productRequest 更新后的商品数据
     * @return 更新后的商品对象
     */
    @PostMapping("/editProduct")
    public CommonResponse editProduct(@RequestParam Long productId, @RequestBody ProductRequest productRequest) {
        try {
            LOGGER.info("Edit product request - productId: {}", productId);
            Product product = productService.updateProduct(productId, productRequest);
            return ResponseBuilder.success(product);  // 返回更新后的完整商品数据
        } catch (Exception e) {
            LOGGER.error("Error editing product", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 删除商品
     * @param productId 商品ID
     * @return 空响应（仅表示操作状态）
     */
    @DeleteMapping("/deleteProduct")
    public CommonResponse deleteProduct(@RequestParam Long productId) {
        try {
            LOGGER.info("Delete product request - productId: {}", productId);
            productService.deleteProduct(productId);  // 调用服务层删除
            return ResponseBuilder.success();  // 无数据返回
        } catch (Exception e) {
            LOGGER.error("Error deleting product", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 关键词搜索商品
     * @param keyword 搜索关键词
     * @return 匹配的商品列表
     */
    @GetMapping("/searchByKeyWord")
    public CommonResponse searchProducts(@RequestParam String keyword) {
        try {
            LOGGER.info("Search products request - keyword: {}", keyword);
            List<Product> products = productService.searchProducts(keyword);
            return ResponseBuilder.success(products);  // 返回列表数据
        } catch (Exception e) {
            LOGGER.error("Error searching products", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 查询所有商品
     * @return 全量商品列表
     */
    @GetMapping("/searchAll")
    public CommonResponse searchAll() {
        try {
            List<Product> products = productService.searchAll();
            return ResponseBuilder.success(products);
        } catch (Exception e) {
            LOGGER.error("Error searching products", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 按商品ID精确查询
     * @param productId 商品ID
     * @return 单个商品详情
     */
    @GetMapping("/searchByProductId")
    public CommonResponse searchByProductId(@RequestParam Long productId) {
        try {
            LOGGER.info("Search product request - productId: {}", productId);
            Product product = productService.searchByProductId(productId);
            return ResponseBuilder.success(product);
        } catch (Exception e) {
            LOGGER.error("Error searching products", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 按分类查询商品
     * @param categoryId 分类ID
     * @return 分类下的商品列表
     */
    @GetMapping("/searchByCategory")
    public CommonResponse searchByCategory(@RequestParam Long categoryId) {
        try {
            LOGGER.info("Search product request - categoryId: {}", categoryId);
            List<Product> product = productService.searchByCategory(categoryId);
            return ResponseBuilder.success(product);
        } catch (Exception e) {
            LOGGER.error("Error searching products", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 按用户ID查询其发布的商品
     * @param userId 用户ID
     * @return 用户关联的商品列表
     */
    @GetMapping("/searchByUserId")
    public CommonResponse searchByUserId(@RequestParam Long userId) {
        try {
            LOGGER.info("Search product request - productId: {}", userId);
            List<Product> products = productService.searchByUserId(userId);
            return ResponseBuilder.success(products);
        } catch (Exception e) {
            LOGGER.error("Error searching products", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /****************** 收藏相关接口 ******************/

    /**
     * 添加商品收藏
     * @param productRequest 包含用户ID和商品ID
     * @return 操作状态
     */
    @PostMapping("/addFavorites")
    public CommonResponse addFavorites(@RequestBody ProductRequest productRequest) {
        try {
            LOGGER.info("Add favorites request - productRequest: {}", productRequest);
            favoritesService.addFavorites(productRequest.getProductId(), productRequest.getUserId());
            return ResponseBuilder.success();
        } catch (Exception e) {
            LOGGER.error("Error adding favorites", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 删除用户的所有收藏
     * @param productRequest 包含用户ID
     * @return 操作状态
     */
    @PostMapping("/deleteByUserId")
    public CommonResponse deleteByUserId(@RequestBody ProductRequest productRequest) {
        try {
            LOGGER.info("Delete favorites request - userId: {}", productRequest.getUserId());
            favoritesService.deleteByUserId(productRequest.getUserId());
            return ResponseBuilder.success();
        } catch (Exception e) {
            LOGGER.error("Error deleting favorites", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }

    /**
     * 查询用户的收藏列表
     * @param productRequest 包含用户ID
     * @return 收藏的商品列表
     */
    @PostMapping("/select")
    public CommonResponse select(@RequestBody ProductRequest productRequest) {
        try {
            LOGGER.info("Select favorites request - userId: {}", productRequest.getUserId());
            List<Product> productList = favoritesService.select(productRequest.getUserId());
            return ResponseBuilder.success(productList);
        } catch (Exception e) {
            LOGGER.error("Error selecting favorites", e);
            return ResponseBuilder.error(e.getMessage());
        }
    }
}
